package com.xander.qqdatabase.aop;

import com.xander.qqdatabase.entity.Log;
import com.xander.qqdatabase.entity.User;
import com.xander.qqdatabase.service.LogService;
import com.xander.qqdatabase.util.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author 叶振东
 * @date 2019-01-18
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    LogService logService;


    @Pointcut("execution(* com.xander.qqdatabase.controller..*.*(..))")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = pjp.proceed();
        try {
            // 获取被拦截的方法
            MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
            Method targetMethod = methodSignature.getMethod();
            // 如果方法上有log注解,代表将日志保存到数据库
            if (targetMethod.isAnnotationPresent(com.xander.qqdatabase.aop.Log.class)) {
                // 当前时间
                Date currentTime = new Date(System.currentTimeMillis());

                // 获取Log注解中note信息
                String note = targetMethod.getAnnotation(com.xander.qqdatabase.aop.Log.class).note();

                // 接收到请求，记录请求内容
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
                String ip = IpUtil.getIpAddr(request);
                String string = (String) pjp.getArgs()[0];
                Integer number = 0;
                if(StringUtils.isNotEmpty(string)){
                    number = Integer.valueOf(string);
                }
                // 当前用户
                User currentUser = (User) request.getSession().getAttribute("user");
                if (currentUser != null) {
                    // 产生日志,保存到数据库
                    Log log = new Log().setUid(currentUser.getUid()).setUsername(currentUser.getUsername())
                            .setNote(note).setNum(number).setIp(ip).setCreateDate(currentTime);
                    logService.insertLog(log);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return proceed;
    }
}
